package com.zzyl.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.base.PageResponse;
import com.zzyl.entity.Member;
import com.zzyl.entity.Reservation;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.TimeCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements ReservationService {

    @Autowired
    private MemberMapper memberMapper;
    @Override
    public Integer getCancelledCount() {
        Long userId = UserThreadLocal.getUserId();//从threadLocal中获取用户id
        DateTime begin = DateUtil.beginOfDay(new Date());//获取当天的开始时间
        DateTime end = DateUtil.endOfDay(new Date());//获取当天的结束时间
        return getBaseMapper().getCancelledCount(userId, begin, end);
    }

    //查询每个时间段剩余预约次数
    @Override
    public List<TimeCountVo> getTimeCount(Long time) {
        LocalDateTime begin = LocalDateTimeUtil.of(time);
        LocalDateTime end=begin.plusHours(24);

        return getBaseMapper().getTimeCount(begin,end);
    }

    @Override
    public void add(Reservation reservation) {
        if (getCancelledCount()>=3){
            throw new RuntimeException("今天的取消次数已达上限,无法进行预约");
        }
        reservation.setStatus(0);//待报到
        try{
            getBaseMapper().insert(reservation);
        }catch (Exception e){
            throw new RuntimeException("预约失败,请确认您没有预约过该时间段");
        }
    }

    @Override
    public PageResponse<Reservation> getByPage(Integer status, Integer pageNum, Integer pageSize) {
        Page<Reservation> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(status!=null,Reservation::getStatus,status)
                .eq(Reservation::getCreateBy,UserThreadLocal.getUserId());
        page = getBaseMapper().selectPage(page, wrapper);

        page.getRecords().stream().forEach(reservation -> {
            Member member = memberMapper.selectById(reservation.getCreateBy());
            if (member != null) {
                reservation.setCreator(member.getName());
            }
        });
        return new PageResponse<Reservation>(page);
    }
}
